import 'dart:core';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_li_ke_jie/constant/app_constant.dart';
import 'package:flutter_li_ke_jie/utils/navigator_util.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../entity/app_pay_result.dart';
import '../pay/pay_result_page.dart';

class WebViewPage extends StatefulWidget {
  final String url;
  final String htmlStr;
  final int tag;//跳转标志 1 vip支付
  final AppPayResult? appPayResult;
  const WebViewPage({Key? key,this.url="",this.htmlStr="",this.tag = 1,this.appPayResult}) : super(key: key);

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> with WidgetsBindingObserver{

  String _title="";
  late WebViewController _webViewController; // 添加一个controller

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);

  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance?.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.paused:
        break;
      case AppLifecycleState.resumed:
        LogUtil.e("-------------------------再次返回页面啦-------------------------");
        //判断是否是支付进来的
        if(widget.tag!=null&&widget.tag==1){
          //跳转支付结果页面
          Navigator.push(context,MaterialPageRoute(builder:
              (BuildContext context)=> PayResultPage(widget.appPayResult!)));
        }
        break;
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
      ),
      body: Stack(
          children: <Widget>[
        WebView(
          initialUrl: widget.url, // 加载的url
          userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Mobile Safari/537.36", // h5 可以通过navigator.userAgent判断当前环境
          javascriptMode: JavascriptMode.unrestricted, // 启用 js交互，默认不启用JavascriptMode.disabled
          onWebViewCreated: (WebViewController web) {
            _webViewController = web;
            // webview 创建调用，
            if(widget.url!=null&&widget.url.isNotEmpty){
              web.loadUrl(widget.url);
            }else{
              web.loadHtmlString(widget.htmlStr);
            }

            web.canGoBack().then((res){
              print(res); // 是否能返回上一级
            });
            web.currentUrl().then((url){
              print(url);// 返回当前url
            });
            web.canGoForward().then((res){
              print(res); //是否能前进
            });
          },
      navigationDelegate: (NavigationRequest request) {
        ///在页面跳转之前调用，TODO isForMainFrame为false,页面不跳转.导致网页内很多链接点击没效果
        //判断是否包含
        if(request.url.contains("https://qr.alipay.com")||request.url.contains("http://qr.alipay.com")){
          launch(request.url);
          //关闭页面 跳转到支付结果页面 轮训
          // NavigatorUtil.goAndFinish(context, PAY_RESULT);
          return NavigationDecision.prevent; // 禁止跳转;
        }
        return NavigationDecision.navigate; // 跳转;
      },
      onPageFinished: (String value) {
        // webview 页面加载调用
        // flutter 调用h5 端方法
        _webViewController
            .evaluateJavascript('document.title')
            .then((title) {
          // 获取网页title
          setState(() {
            _title = title;
          });
        });
      },
    )
    ],
    ),
    );
  }
}

